package com.atgouwu.mall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atgouwu.mall.auth.feign.MemberFeignService;
import com.atgouwu.mall.auth.feign.ThirdPartFeignService;
import com.atgouwu.mall.auth.vo.UserRegisterVo;
import com.atgouwu.mall.common.constant.AuthServerConstant;
import com.atgouwu.mall.common.exception.BizCodeEnum;
import com.atgouwu.mall.common.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 注册
 */
@Api(tags = "注册")
@RestController
@RequestMapping("auth/register")
public class RegisterController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ThirdPartFeignService thirdPartFeignService;
    @Autowired
    private MemberFeignService memberFeignService;

    //发送短信验证码,存入redis
    @ApiOperation(value = "发送短信验证码")
    @GetMapping(value = "/api/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone) {
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)) { //60s内不能再发
            long currentTime = Long.parseLong(redisCode.split("_")[1]); //存入redis时间
            if (System.currentTimeMillis() - currentTime < 60000) { //当前时间-存入时间<60s不能再发
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        int code = (int) ((Math.random() * 9 + 1) * 100000); //随机生成6位数验证码
        String codeNum = String.valueOf(code);
        String redisStorage = codeNum + "_" + System.currentTimeMillis(); //验证码+时间戳(接口防刷)
        stringRedisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, redisStorage, 10, TimeUnit.MINUTES); //存入redis{"sms:code:17719996372":"268975_17867868",有效10分钟}
        return thirdPartFeignService.sendCode(phone, codeNum); //发送短信验证码(远程调用third_party第三方服务)
    }

//    //注册(前后端不分离)
//    @PostMapping(value = "/register")
//    public String register(@Valid UserRegisterVo vos, BindingResult result, RedirectAttributes attributes) {
//        if (result.hasErrors()) { //JSR303参数校验有错误
//            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
//            attributes.addFlashAttribute("errors", errors);
//            return "redirect:http://auth.gulimall.com/reg.html"; //效验出错回到注册页面
//        }
//        String code = vos.getCode();
//        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone()); //获取redis里验证码
//        if (!StringUtils.isEmpty(redisCode)) { //校验验证码
//            if (code.equals(redisCode.split("_")[0])) {
//                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone()); //删除验证码(令牌机制)
//                R register = memberFeignService.register(vos);
//                if (register.getCode() == 0) { //成功到登录页
//                    return "redirect:http://auth.gulimall.com/login.html";
//                } else {
//                    Map<String, String> errors = new HashMap<>();
//                    errors.put("msg", register.getData("msg", new TypeReference<String>() {
//                    }));
//                    attributes.addFlashAttribute("errors", errors);
//                    return "redirect:http://auth.gulimall.com/reg.html"; //效验出错回到注册页面
//                }
//            } else {
//                Map<String, String> errors = new HashMap<>();
//                errors.put("code", "验证码错误");
//                attributes.addFlashAttribute("errors", errors);
//                return "redirect:http://auth.gulimall.com/reg.html"; //效验出错回到注册页面
//            }
//        } else {
//            Map<String, String> errors = new HashMap<>();
//            errors.put("code", "验证码错误");
//            attributes.addFlashAttribute("errors", errors);
//            return "redirect:http://auth.gulimall.com/reg.html"; //效验出错回到注册页面
//        }
//    }

    //提交注册(前后端分离)
    @ApiOperation(value = "提交注册")
    @PostMapping(value = "/api/register")
    public R register(@RequestBody @Valid UserRegisterVo vos, BindingResult result) {
        if (result.hasErrors()) { //JSR303参数校验(java自带,只需在实体类上注解,BindingResult接受结果)
            Map<String, String> error = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            String errors = error.values().stream().reduce((s1, s2) -> s1 + "," + s2).orElse("");
            return R.error().put("msg", errors);
        }
        String code = vos.getCode();
        String redisCode = stringRedisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone()); //获取redis里验证码
        if (!StringUtils.isEmpty(redisCode)) { //校验redis验证码非空(60s过期)
            if (code.equals(redisCode.split("_")[0])) { //校验验证码与reids中相同
                stringRedisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vos.getPhone()); //删除验证码(令牌机制)
                R register = memberFeignService.register(vos); //注册(远程调用member会员服务)
                if (register.getCode() == 200) { //成功
                    return R.ok();
                } else {
                    return R.error().put("msg", register.getData("msg", new TypeReference<String>() {
                    }));
                }
            } else {
                return R.error().put("msg", "验证码错误");
            }
        } else {
            return R.error().put("msg", "验证码过期,请重新获取验证码!");
        }
    }

}
